package ControllerDashBoard

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"time"
	"ustcLab/conf"
	"ustcLab/server/common/queueUtils"
	"ustcLab/server/dao/bean"
	"ustcLab/server/dao/daoimpl"
	"ustcLab/server/service/ServiceDashBoard"
	"ustcLab/server/service/ServiceDataFresh"
)

func HandlerShow(ctx *gin.Context) {
	ServiceDashBoard.Show()
	ctx.String(200, "fresh success.")
}

func HandlerPrint(ctx *gin.Context) {
	ctx.String(200, "test message.")
}

func HandlerRecv(ctx *gin.Context) {
	log.Println(time.Now().Unix())
	buf, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		ctx.String(200, err.Error())
		log.Println("[Debug]err: " + err.Error())
	}

	//log.Println("[Debug]HandlerRecv: " + string(buf))
	request := &bean.TPythonDataInfo{}
	err = json.Unmarshal(buf, request)
	if err != nil {
		ctx.String(200, err.Error())
		log.Println("[Debug]err: " + err.Error())
	}
	//返回res为*bean.DashBoardResponse类型
	//fmt.Println(request)
	err1, res := ServiceDataFresh.DataTransfer(request)
	if err1 != nil {
		ctx.String(200, err1.Error())
		log.Println("[Debug]err: " + err1.Error())
	}
	//得到队列
	queue := queueUtils.GetQueue()
	//入队
	queue.Push(res)
	log.Println("[Debug] handle recv success.")
	log.Println("End in: ", time.Now().Unix())
	ctx.String(200, "success")
}

func HandlerDashBoard(ctx *gin.Context) {
	queue := queueUtils.GetQueue()
	//出队列
	node, err := queue.Pull()
	if err != nil {
		ctx.String(200, err.Error())
		log.Println("[Debug]err: " + err.Error())
	}
	resp := &bean.DashBoardResponse{
		NServer:          node.NServer,
		Data:             node.Data,
		IsInEmergency:    false,
		MessageEmergency: "",
	}
	//if res, resVal, ok := ServiceRuler.CheckRuler2(data); !ok {
	//	resp.IsInEmergency = true
	//	resp.MessageEmergency = fmt.Sprintf(
	//		"[Warning]异常指标清单：%s，观测值:[%s]，%s",
	//		strings.Join(res, ","), strings.Join(resVal, ","), conf.ErrorEmergencyPostFix)
	//}
	ctx.JSON(200, resp)
}

func HandlerMonitorInfo(ctx *gin.Context) {
	count, data, err := daoimpl.QueryMonitorInfo()
	if err != nil {
		ctx.JSON(400, gin.H{
			"error": "database query error!",
		})
	}
	if count == 0 {
		log.Printf("[HandlerMonitorInfo] %s\n", conf.ErrorDatabaseQuery)
		ctx.JSON(200, gin.H{
			"error": conf.ErrorDatabaseQuery,
		})
		return
	}
	resp := &bean.MonitorInfoResponse{
		FId:                 data[0].FId,
		FName:               data[0].FName,
		FHeartRadio:         data[0].FHeartRadio,
		FBloodPressureUpper: data[0].FBloodPressureUpper,
		FBloodPressureLower: data[0].FBloodPressureLower,
		FBreathe:            data[0].FBreathe,
		FMedicines:          data[0].FMedicines,
		FMessageEmergency:   data[0].FMessageEmergency,
		FModifyTime:         data[0].FModifyTime.Format("04:05"),
		FSpo2:               data[0].FSpo2,
		FSao2:               data[0].FSao2,
		FO2:                 data[0].FO2,
		FN2o:                data[0].FN2o,
	}
	//if res, resVal, ok := ServiceRuler.CheckRuler(data[0]); !ok {
	//	resp.FIsInEmergency = true
	//	resp.FMessageEmergency = fmt.Sprintf(
	//		"[Warning]异常指标清单：%s，观测值:[%s]，%s",
	//		strings.Join(res, ","), strings.Join(resVal, ","), conf.ErrorEmergencyPostFix)
	//}
	log.Println("[Debug] Emergency: ", resp.FMessageEmergency)
	ctx.JSON(200, resp)
}
